package edu.ynu.se.xiecheng.achitectureclass.project.service;

import edu.ynu.se.xiecheng.achitectureclass.project.dto.CameraResponse;
import edu.ynu.se.xiecheng.achitectureclass.project.entity.CameraData;
import edu.ynu.se.xiecheng.achitectureclass.project.dao.CameraDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Date;
import java.util.Optional;

@Service
public class CameraService {

    @Autowired
    private CameraDataRepository cameraDataRepository;

    @Autowired
    private TokenService tokenService;

    // 硬编码 deviceSerial
    private static final String DEVICE_SERIAL = "L29334649";

    // 日志记录器
    private static final Logger logger = LoggerFactory.getLogger(CameraService.class);

    // 每15分钟执行一次
    @Scheduled(fixedRate = 15 * 60 * 1000)
    public void captureAndSaveImage() {
        String accessToken = tokenService.getCameraToken();
        String url = "https://open.ys7.com/api/lapp/device/capture";

        // 打印请求 URL 和 accessToken
        logger.info("Request URL: {}", url);
        logger.info("Access Token: {}", accessToken);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        logger.info("Request Headers: {}", headers);

        // 设置请求体
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("accessToken", accessToken);
        map.add("deviceSerial", DEVICE_SERIAL); // 使用硬编码的设备号
        map.add("channelNo", "1");
        map.add("quality", "1");
        logger.info("Request Body: {}", map);

        // 构建请求实体
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        // 发送请求
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<CameraResponse> response = restTemplate.postForEntity(url, request, CameraResponse.class);

        // 打印响应状态码和响应体
        logger.info("Response Status Code: {}", response.getStatusCode());
        logger.info("Response Body: {}", response.getBody());

        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            String picUrl = response.getBody().getData().getPicUrl();
            logger.info("Captured Image URL: {}", picUrl);

            // 查询现有数据
            Optional<CameraData> existingData = cameraDataRepository.findByDeviceSerial(DEVICE_SERIAL);

            // 更新或插入数据
            CameraData cameraData = existingData.orElse(new CameraData());
            cameraData.setPhotoUrl(picUrl);
            cameraData.setCreateTime(new Date());
            cameraData.setDeviceSerial(DEVICE_SERIAL);
            cameraDataRepository.save(cameraData);
            logger.info("Camera data updated in database: {}", cameraData);
        } else {
            logger.error("Failed to capture image. Response: {}", response);
            throw new RuntimeException("Failed to capture image");
        }
    }
    public String getLatestPhotoUrlByDeviceSerial(String deviceSerial) {
        Optional<CameraData> latestCameraData = cameraDataRepository.findLatestByDeviceSerial(deviceSerial);
        return latestCameraData.map(CameraData::getPhotoUrl).orElse(null);
    }

}